/*
 * Copyright 2006-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.martinimix.context.support;

import java.util.LinkedHashMap;


import com.bluemartini.dna.DNABasePair;
import com.bluemartini.dna.DNAList;
import com.bluemartini.dna.DNAListArray;
import com.bluemartini.dna.DomainElement;

/**
 * Provides a domain dictionary based reference data linked hash map.
 * 
 * @author Scott Rossillo
 *
 */
final class BlueMartiniDomainDictionaryDataMap extends LinkedHashMap {
	
	private static final long serialVersionUID = 1L;

	private final String name;
	
	/**
	 * Constructs a new linked has map from the contents of the given
	 * domain element 
	 * 
	 * @param domainElement the <code>DomainElement</code> providing
	 * data for this map
	 */
	protected BlueMartiniDomainDictionaryDataMap(DomainElement domainElement) {
		
		if(domainElement == null) {
			throw new IllegalArgumentException("domain element cannot be null!");
		}
		
		this.name = domainElement.getName();
		DNAList noSelectionValue = domainElement.getNotSelectedValue();
		
		if(noSelectionValue != null && !noSelectionValue.isEmpty()) {
			if(domainElement.getString("code") == null) {
				
			}
			add(domainElement.getNotSelectedValue());
		}
		addAll(domainElement.getDomainValues());
	}
	
	private void add(DNAList value) {
		
		DNABasePair code = value.getBasePair("code");
		String decode = value.getString("decode"); 
		
		if(code == null || decode == null) {
			throw new InvalidDomainElementException(name, value);
		}
		
		super.put(code.getValue().toString(), decode);
	}
	
	private void addAll(DNAListArray values) {
		
		for(int i = 0; i < values.size(); i++) {
			add(values.elementAt(i));
		}
	}

}
